<?php

/**
 * 文章标签（关键词）管理操作类
 * @author 王志昂
 * @create 2013年6月17日 23:49:04
 */
class Business_Tags
{

    protected $_tagsTable;

    protected $_tagsrelTable;

    protected static $_instance;

    public static function getInstance()
    {
        if (empty(self::$_instance)) {
            self::$_instance = new Business_Tags();
        }
        return self::$_instance;
    }

    public function __construct()
    {
        $this->_tagsTable = Zend_Registry::get('database')->tags;
        $this->_tagsrelTable = Zend_Registry::get('database')->tagsrel;
    }

    /**
     * 将标签的名称插入或更新数据库
     * 
     * @param string $tag            
     * @return array NULL
     */
    public function setTag($tag)
    {
        $bind = array(
            $this->_tagsTable->name => $tag,
            $this->_tagsTable->urlencode => urlencode($tag)
        );
        
        try {
            $db = Utility_Db::getInstance()->conn();
            $result = $db->insert($this->_tagsTable->tablename, $bind);
            if ($result) {
                $rtn = array(
                    'errorcode' => 0,
                    'errormsg' => 'success',
                    'result' => $db->lastInsertId()
                );
            } else {
                $rtn = array(
                    'errorcode' => - 1,
                    'errormsg' => 'failed'
                );
            }
        } catch (Exception $e) {
            // 没有更新也是成功
            if ($e->getCode() == 1062) {
                $result = Utility_Db::getInstance()->conn()
                    ->select()
                    ->from($this->_tagsTable->tablename, 'id')
                    ->where($this->_tagsTable->urlencode . '=?', urlencode($tag))
                    ->query()
                    ->fetch();
                $rtn = array(
                    'errorcode' => 0,
                    'errormsg' => 'not update',
                    'result' => $result['id']
                );
            } else {
                $rtn = array(
                    'errorcode' => - 2,
                    'errormsg' => $e->getMessage()
                );
            }
        }
        return $rtn;
    }

    /**
     * 将标签和文章的关系插入数据库
     * 
     * @param int $articleid            
     * @param int $tagid            
     * @return array
     */
    public function setTagAndArticleRel($articleid, $tagid)
    {
        $bind = array(
            $this->_tagsrelTable->articleid => $articleid,
            $this->_tagsrelTable->tagid => $tagid
        );
        
        try {
            $result = Utility_Db::getInstance()->conn()->insert($this->_tagsrelTable->tablename, $bind);
            if ($result) {
                $rtn = array(
                    'errorcode' => 0,
                    'errormsg' => 'success'
                );
            } else {
                $rtn = array(
                    'errorcode' => - 1,
                    'errormsg' => 'failed'
                );
            }
        } catch (Exception $e) {
            if ($e->getCode() == 1062) {
                $rtn = array(
                    'errorcode' => 0,
                    'errormsg' => 'success'
                );
            } else {
                $rtn = array(
                    'errorcode' => - 2,
                    'errormsg' => $e->getMessage()
                );
            }
        }
        return $rtn;
    }

    /**
     * 删除文章和标签关系
     * 
     * @param unknown $articleid            
     * @param unknown $tagid            
     * @return multitype:number NULL
     */
    public function deleteTagAndArticleRel($articleid, $tagid)
    {
        $where = array(
            $this->_tagsrelTable->articleid . '=?' => $articleid,
            $this->_tagsrelTable->tagid . '=?' => $tagid
        );
        
        try {
            $result = Utility_Db::getInstance()->conn()->delete($this->_tagsrelTable->tablename, $where);
            
            $rtn = array(
                'errorcode' => 0,
                'errormsg' => 'success'
            );
        } catch (Exception $e) {
            $rtn = array(
                'errorcode' => - 2,
                'errormsg' => $e->getMessage()
            );
        }
        return $rtn;
    }

    public function getTagIdByUrlencode($urlencode)
    {
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_tagsTable->tablename, $this->_tagsTable->id)
            ->where($this->_tagsTable->urlencode . '=?', $urlencode)
            ->query()
            ->fetch();
        return $result[$this->_tagsTable->id];
    }

    /**
     * 根据文章id获取一串标签的id
     * 
     * @param int $articleid            
     * @return array
     */
    public function getTagsInId($articleid)
    {
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_tagsrelTable->tablename, $this->_tagsrelTable->tagid)
            ->where($this->_tagsrelTable->articleid . '=?', $articleid)
            ->query()
            ->fetchAll();
        
        $tags = array();
        foreach ($result as $item) {
            $tags[] = $item[$this->_tagsrelTable->tagid];
        }
        return $tags;
    }

    public function getTagByUrlencode($tagid)
    {
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_tagsTable->tablename, $this->_tagsTable->urlencode)
            ->where($this->_tagsTable->id . '=?', $tagid)
            ->query()
            ->fetch();
        return $result[$this->_tagsTable->urlencode];
    }

    /**
     * 根据文章id获取一串标签的Urlencode值
     * 
     * @param int $articleid            
     * @return array
     */
    public function getTagsInUrlencode($articleid)
    {
        $result = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_tagsrelTable->tablename, $this->_tagsrelTable->tagid)
            ->where($this->_tagsrelTable->articleid . '=?', $articleid)
            ->query()
            ->fetchAll();
        
        $tags = array();
        foreach ($result as $item) {
            $tags[] = $this->getTagByUrlencode($item[$this->_tagsrelTable->tagid]);
        }
        return $tags;
    }

    /**
     * 获取所有的标签，并包含标签出现的次数
     */
    public function getAllTagsWithCount()
    {
        $tagsArr = Utility_Db::getInstance()->conn()
            ->select()
            ->from($this->_tagsTable->tablename)
            ->query()
            ->fetchAll();
        
        $result = array();
        foreach ($tagsArr as $tag) {
            if ($tag[$this->_tagsTable->urlencode] == '') {
                continue;
            }
            $tmp = Utility_Db::getInstance()->conn()
                ->select()
                ->from($this->_tagsrelTable->tablename, 'count(*)')
                ->where($this->_tagsrelTable->tagid . '=?', $tag[$this->_tagsTable->id])
                ->query()
                ->fetchAll();
            
            $tmp2 = current($tmp);
            $result[$tag[$this->_tagsTable->urlencode]] = $tmp2['count(*)'];
        }
        arsort($result);
        $result = array_slice($result, 0, 20);
        return $result;
    }

    /**
     * 格式化标签云算法
     */
    public function formatTagsCloud(array $tags)
    {
        $defaults = array(
            'smallest' => 8,
            'largest' => 22,
        );
        
        $maxCount = current($tags);
        $minCount = end($tags);
        $largest = $defaults['largest'];
        $smallest = $defaults['smallest'];
        $spread = $maxCount - $minCount;
        $fontSpread = $largest - $smallest;
        $fontStep = $fontSpread / $spread;
        $rtn = array();
        foreach ($tags as $tag => $count) {
            $fontSize = $smallest + (($count - $minCount) * $fontStep);
            $rtn[$tag] = array(
                'count' => $count,
                'fontSize' => $fontSize
            );
        }
        krsort($rtn);
        return $rtn;
    }
}